import React, {PureComponent} from 'react';
import PropTypes from 'prop-types';
import {Row, Col, Form, Button, Divider, Table, message as msg, Modal, Alert} from 'antd';
import {PAGE, TABLE, PAGINATION_OPTIONS, FORM_OPTIONS} from '../constants';
import TextInput from 'Shared/components/TextInput';
import {computeSelectedRows, conventSorter} from './utils';
import styles from './style.css';
import {getPersonnels} from './api';
const FormItem = Form.Item;
import WrappedTag from '../common/WrappedTag';

class PersonnelSelectPanel extends PureComponent {
    state = {
        userName: '',
        name: '',
        isFetching: false,
        data: {},
        message: '',
        showTags: false,
        pageIndex: PAGE.index,
        pageSize: PAGE.smallSize,
        currentCondition: {},
        selectedRowKeys: [],
        selectedRows: [],
    }
    
    handleTableChange = (pagination, filters, sorter) => {
        const oldCondition = {...this.state.currentCondition};
        if(pagination.current - 1 === oldCondition.pageIndex && pagination.pageSize === oldCondition.pageSize) {
            const sortOptions = conventSorter(sorter);
            const condition = Object.assign({}, oldCondition, sortOptions, {
                pageIndex: pagination.current - 1
            });
            this.onQuery(condition);
            this.setState({
                sortField: sortOptions.sortField,
                isDesc: sortOptions.isDesc
            });
        }
    }

    handleFilterPressEnter = (value, name) => {
        this.setState({[name]: value}, this.onClickSearchBtn);
    }
        
    toggleShowTags=() => {
        this.setState({
            showTags: !this.state.showTags
        });
    }

    onQuery = condition => {
        this.setState({isFetching: true});
        getPersonnels(condition)
            .then(res => {
                if(res.ok)
                    this.setState({
                        isFetching: false,
                        message: '',
                        data: res.data,
                        currentCondition: condition
                    });
                else
                    this.setState({
                        isFetching: false,
                        data: [],
                        message: res.message
                    });
            });
    }

    onClickSearchBtn = () => {
        const condition = {
            userName: this.state.userName,
            name: this.state.name,
            pageIndex: PAGE.index,
            pageSize: this.state.pageSize,
            sortField: this.state.sortField,
            isDesc: this.state.isDesc
        };
        this.onQuery(condition);
    }

    onPageIndexChange = current => {
        const condition = {...this.state.currentCondition};
        condition.pageIndex = current - 1;
        this.onQuery(condition);
    }

    onPageSizeChange = (current, pageSize) => {
        const condition = {...this.state.currentCondition};
        condition.pageIndex = PAGE.index;
        condition.pageSize = pageSize;
        this.onQuery(condition);
        this.setState({
            pageSize
        });
    }

    onChange = (value, name) => {
        this.setState({[name]: value});
    }

    onClickReset = () => {
        this.setState({
            userName: '',
            name: ''
        });
    }

    onSubmit = () => {
        if(!this.state.selectedRows.length)
            return msg.warn(this.props.intl.formatMessage({
                id: 'personnelSelectPanel.validate.addedItem',
                defaultMessage: '请选择人员数据'
            }));
        this.props.onSelect(this.state.selectedRows);
    }

    onSelectChange = (selectedRowKeys, selectedRows) => {
        this.setState({
            selectedRowKeys,
            selectedRows,
            showConfirmButton: selectedRowKeys.length > 0
        });
    }

    onClearAll=() => {
        this.setState({
            selectedRowKeys: [],
            selectedRows: []
        });
    }

    onDelete=id => {
        const keys = this.state.selectedRowKeys.filter(k => k !== id);
        const rows = this.state.selectedRows.filter(r => r.id !== id);
        this.setState({
            selectedRowKeys: [...keys],
            selectedRows: [...rows]
        });
    }

    render() {
        const {formatMessage} = this.props.intl;
        const {isFetching, data} = this.state;
        const {pageIndex, pageSize} = this.state.currentCondition;
        const columns = [
            {
                title: formatMessage({
                    id: 'personnelSelectPanel.column.userName',
                    defaultMessage: '编号'
                }),
                sorter: true,
                dataIndex: 'userName'
            }, {
                title: formatMessage({
                    id: 'personnelSelectPanel.column.name',
                    defaultMessage: '姓名'
                }),
                dataIndex: 'name',
                sorter: true,
            }
        ];
        const pagination = {
            total: data.totalElements,
            current: pageIndex + 1,
            pageSize,
            onShowSizeChange: this.onPageSizeChange,
            onChange: this.onPageIndexChange,
            ...PAGINATION_OPTIONS
        };
        const rowSelection = {
            selectedRowKeys: this.state.selectedRowKeys,
            onChange: (selectedRowKeys, selectedRows) => {
                const rows = computeSelectedRows(this.state.selectedRowKeys, this.state.selectedRows, selectedRowKeys, selectedRows);
                this.setState({
                    selectedRowKeys,
                    selectedRows: rows
                });
            }
        };
        const alertMessage = (
            <div>
                <span>
                    {this.props.intl.formatMessage({
                        id: 'personnelSelectPanel.alertMessage.span',
                        defaultMessage: '已选择'
                    })}
                    <a onClick={this.toggleShowTags}>
                        {this.state.selectedRows.length}
                        {this.props.intl.formatMessage({
                            id: 'personnelSelectPanel.alertMessage.a.number',
                            defaultMessage: '项'
                        })}
                    </a>
                    {this.props.intl.formatMessage({
                        id: 'personnelSelectPanel.alertMessage.comma',
                        defaultMessage: '，'
                    })}
                    <a onClick={this.onClearAll} className={styles.clearAllTag}>
                        {this.props.intl.formatMessage({
                            id: 'personnelSelectPanel.alertMessage.deleteAll',
                            defaultMessage: '清除选择'
                        })}
                    </a>
                    <Button
                        size="small"
                        type="primary"
                        className={styles.partBtn}
                        onClick={this.onSubmit}>
                        {this.props.intl.formatMessage({
                            id: 'personnelSelectPanel.btn.confirm',
                            defaultMessage: '确认'
                        })}
                    </Button>
                </span>
                {this.state.showTags && (
                    <div style={{
                        marginTop: '8px'
                    }}>
                        {this.state.selectedRows.map(r => (
                            <WrappedTag key={r.id} closable id={r.id} onClose={this.onDelete}>
                                {r.name}
                            </WrappedTag>
                        ))}
                    </div>
                )}
            </div>
        );
        const {brands} = this.props.initEnumData;

        return (
            <Modal
                title={formatMessage({
                    id: 'personnelSelectPanel.show.addedItemQuery',
                    defaultMessage: '人员信息查询'
                })}
                width="60%"
                maskClosable={false}
                footer={null}
                destroyOnClose={true}
                wrapClassName={styles.dataSelectModal}
                visible={true}
                onCancel={this.props.onCancel}>
                <Row className="form-standard">
                    <Col {...FORM_OPTIONS.col}>
                        <FormItem label={formatMessage({
                            id: 'personnelSelectPanel.userName',
                            defaultMessage: '编号'
                        })} {...FORM_OPTIONS.item}>
                            <TextInput
                                name="userName"
                                value={this.state.userName}
                                onPressEnter={this.handleFilterPressEnter}
                                onBlur={this.onChange} />
                        </FormItem>
                    </Col>
                    <Col {...FORM_OPTIONS.col}>
                        <FormItem label={formatMessage({
                            id: 'personnelSelectPanel.name',
                            defaultMessage: '姓名'
                        })} {...FORM_OPTIONS.item}>
                            <TextInput
                                name="name"
                                value={this.state.name}
                                onPressEnter={this.handleFilterPressEnter}
                                onBlur={this.onChange} />
                        </FormItem>
                    </Col>
                    <Col {...FORM_OPTIONS.col} className={styles['inline-button']}>
                        <Button
                            type="primary"
                            loading={isFetching}
                            onClick={this.onClickSearchBtn}>
                            {formatMessage({
                                id: 'personnelSelectPanel.btn.query',
                                defaultMessage: '查询'
                            })}
                        </Button>
                        <Button key="clear" onClick={this.onClickReset}>{formatMessage({
                            id: 'personnelSelectPanel.btn.reset',
                            defaultMessage: '重置'
                        })}</Button>
                    </Col>
                </Row>
                <Divider className={styles.divider}/>
                <Alert className={styles.alert} type="info" message={alertMessage} showIcon />
                <Table
                    className="white-space-nowrap"
                    rowKey="id"
                    dataSource={data.content}
                    rowClassName={styles.tableCursor}
                    columns={columns}
                    loading={isFetching}
                    pagination={pagination}
                    onChange={this.handleTableChange}
                    rowSelection={rowSelection}
                    {...TABLE}/>
            </Modal >
        );
    }
}

PersonnelSelectPanel.propTypes = {
    onSelect: PropTypes.func.isRequired,
    intl: PropTypes.object,
    onCancel: PropTypes.func
};
import {injectIntl} from './intl';
import {connect} from 'react-redux';
import {createSelector} from 'reselect';
const getinitEnumData = createSelector(
    state => state.getIn(['page', 'domainData', 'initData']),
    init => {
        const initData = init.toJS();
        const brands = initData.brands ? initData.brands.map(item => ({
            text: `(${item.brandCode}) ${item.brandName}`,
            value: item.brandId
        })) : [];
        return {
            brands,
        };
    }
);
const mapStateToProps = state => ({
    initEnumData: getinitEnumData(state),
});

export default connect(mapStateToProps, null)(injectIntl(PersonnelSelectPanel));
